import headerNavTpl from './headerNav.html';

function headerNavComponent($rootScope, $interval, $log, $http, ngDialog, authenticate) {
  'ngInject';
  var directive = {
    restrict: 'E',
    replace: true,
    templateUrl: headerNavTpl,
    controller: headerNavController,
    controllerAs: 'headerNav',
    bindToController: true
  };

  function headerNavController(paFetchService) {
    'ngInject';

    let _this = this;

    // 判断一级菜单应该用什么icon
    this.getIconClass = (menuItem) => {
      if (menuItem.name === '首页') {
        return 'fa fa-home';
      } else if (menuItem.name === '人员管理') {
        return 'fa fa-users';
      } else if (menuItem.name === '设备管理') {
        return 'fa fa-cube';
      } else if (menuItem.name === '安全活动') {
        return 'fa fa-clipboard';
      } else if (menuItem.name === '内业资料管理') {
        return 'fa fa-book';
      } else if (menuItem.name === '日常巡查') {
        return 'fa fa-camera';
      } else if (menuItem.name === '考核管理') {
        return 'fa fa-list-alt';
      } else if (menuItem.name === '统计分析') {
        return 'fa fa-pie-chart';
      } else if (menuItem.name === '智能监控') {
        return 'fa fa-video-camera';
      }
      // else if (menuItem.name === '危险源管理') {
      //   return 'fa fa-exclamation-triangle';
      // }
    };

    // 菜单数据
    this.menus = [{
      name: '首页',
      srefName: 'main',
      subMenus: [],
    }, {
      name: '人员管理',
      srefName: '',
      subMenus: [{
        name: '人员信息',
        srefName: 'workerInfo',
        parent: '人员管理',
      }, {
        name: '施工队/部门',
        srefName: 'constructionTeam',
        parent: '人员管理',
      },],
      // {
      //         name: '人员定位',
      //         srefName: 'personnelLocation',
      //         parent: '人员管理',
      //       },
    }, {
      name: '设备管理',
      srefName: '',
      subMenus: [{
        name: '设备信息',
        srefName: 'equipmentInfo',
        parent: '设备管理',
      }, {
        name: '维修保养',
        srefName: 'maintenance',
        parent: '设备管理',
      }, {
        name: '设备检测',
        srefName: 'equipmentInspection',
        parent: '设备管理',
      }, ],
    }, {
      name: '安全活动',
      srefName: '',
      subMenus: [{
        name: '安全会议',
        srefName: 'meeting',
        parent: '安全活动',
      }, {
        name: '安全教育培训',
        srefName: 'techTraining',
        parent: '安全活动',
      }, {
        name: '安全技术交底',
        srefName: 'safeDisclosure',
        parent: '安全活动',
      }, ],
    }, {
      name: '日常巡查',
      srefName: '',
      subMenus: [{
        name: '巡查记录',
        srefName: 'dailyCheck',
        parent: '日常巡查',
      }, {
        name: '巡查内容',
        srefName: 'inspectContent',
        parent: '日常巡查',
      },
      {
        name: '巡查材料打印',
        srefName: 'inspectMaterialToPrint',
        parent: '日常巡查',
      },
       ],
    }, {
      name: '考核管理',
      srefName: '',
      subMenus: [{
        name: '平安考核',
        srefName: 'assessmentPeace',
        parent: '考核管理',
      }, {
        name: '平安考核标准',
        srefName: 'checkConfiguration',
        parent: '考核管理',
      }],
    }, {
      name: '内业资料管理',
      srefName: 'documentMgt',
      subMenus: [],
    }, {
      name: '统计分析',
      srefName: 'statisticAnalyze',
      subMenus: [],
    },
    {
      name: '智能监控',
      srefName: 'videoMonitor',
      subMenus: [],
    },
    // {
    //   name: '危险源管理',
    //   srefName: '',
    //   subMenus: [{
    //     name: '危险源信息',
    //     srefName: 'dangerManagement',
    //   }, {
    //     name: '巡检记录',
    //     srefName: 'dangerRecords',
    //   }],
    // },
    ];

    // 三级导航菜单（首页）
    this.menus3 = [{
      name: '首页',
      srefName: 'main',
      subMenus: [
        {
          name: '问题追踪',
          srefName: 'inspectContent4Problems',
          parent: '首页',
          childName: [
            {
              name: '内容详情',
              srefName: 'rectificationDetail',
              parent: '问题追踪',
            }
          ]
        },{
          name: '项目公告',
          srefName: 'projectNotice',
          parent: '首页',
          childName: [
            {
             name: '公告详情',
             srefName: 'announcementDetail',
             parent: '项目公告',
            },{
             name: '发布公告',
             srefName: 'announcement',
             parent: '项目公告',
            },
          ]
        }
      ],
    },];

    /** 方法 */

    /** 一级菜单hover时添加hover样式判断 */
    this.setSubMenuActive = (superMenuItem, flag) => {
      // 判断是否有二级菜单
      this.menus.forEach((item) => {
        if (item.subMenus[0]) {
          if (item.name === superMenuItem.name) {
            item.hover = flag;
          }
        }
      });
    };

    // 判断是否有二级菜单，跳转页面
    this.goPage = (superMenuItem) => {
      this.menus.forEach((item) => {
        if (!item.subMenus[0]) {
          if (item.name === superMenuItem.name) {
            $state.go(item.srefName);
          }
        }
      });
    }

    /** 一级菜单visited样式判断 */
    this.isVisited = (superMenuItem) => {
      let currentViewName = $state.$current.name;
      let isVisited = false;
      // 如果是一级菜单页面 直接返回true
      if (superMenuItem.srefName == currentViewName) {
        isVisited = true;
      }

      // 如果是二级菜单页面,遍历二级菜单
      superMenuItem.subMenus.forEach((item) => {
        if (item.srefName == currentViewName) {
          isVisited = true;
        }
      });

      return isVisited;
    };

    /** 是否有二级菜单 */
    this.hasSubMenus = (superMenu) => {
      let subMenus = superMenu.subMenus;
      return subMenus ? (subMenus.length == 0 ? false : true) : false;
    };

    /** 返回当前所在页面即父页面名称 */
    this.getCurrentLocationStacks = () => {
      let locationStacks = {
        superMenuName: '',
        subMenuName: '',
        childName: ''
      };
      let currentViewName = $state.$current.name;
      this.menus.forEach((item) => {
        if (item.srefName == currentViewName) {
          locationStacks.superMenuName = item.name;
        }
      });
      if (locationStacks.superMenuName) return locationStacks.superMenuName;
      this.menus.forEach((item) => {
        item.subMenus.forEach((subItem) => {
          if (subItem.srefName == currentViewName) {
            locationStacks.superMenuName = subItem.parent;
            locationStacks.subMenuName = subItem.name;
            return;
          }
        })
      });
      // 三级导航
      this.menus3.forEach((item) => {
        item.subMenus.forEach((subItem) => {
          if (subItem.srefName == currentViewName) {
            locationStacks.superMenuName = subItem.parent;
            locationStacks.subMenuName = subItem.name;
            return;
          }
        })
      });

      this.menus3.forEach((item) => {
        item.subMenus.forEach((subItem) => {
          if (subItem.childName) {
            subItem.childName.forEach((param) => {
              if (param.srefName == currentViewName) {
                locationStacks.superMenuName = subItem.parent;
                locationStacks.subMenuName = subItem.name;
                locationStacks.childName = param.name;
                return;
              }
            })
          }
        })
      })
      if (!locationStacks.superMenuName || !locationStacks.subMenuName) {
        return '';
      } else if (locationStacks.childName) {
        return `${locationStacks.superMenuName} > ${locationStacks.subMenuName} > ${locationStacks.childName}`;
      } else {
        return `${locationStacks.superMenuName} > ${locationStacks.subMenuName}`;
      }
    }

    this.changePwd = () => {
      ngDialog.open({
        template: 'pwdDialog',
        className: 'ngdialog-theme-default pa-special-check-item-list-theme',
        controllerAs: 'vm',
        controller: function trainClarifyCtrl($rootScope, $http, $scope) {
          'ngInject';
          this.userInfo = {};

          // 获取登陆用户信息GET /api/safesite/user/getCurrentUser 获取登录用户

          this.getUserInfo = () => {
              $http
                .get(`${SERVER_CONTEXT}/api/safesite/user/getCurrentUser`)
                .then((resp) => {
                  if (resp.statusText == 'OK') {
                    this.userInfo.loginName = resp.data.loginName;
                  }
                });
            }
            // 保存修改密码
          this.submit = (param) => {
            // 修改表单是否提交过状态
            param.$submitted = true;
            // 表单校验
            if (param.$invalid) {
              return false;
            } else if (param.confirmPassword.$viewValue != param.newPassWord.$viewValue) {
              layer.alert('确认密码和新密码不一致');
              return false;
            } else {
              $http
                .put(`${SERVER_CONTEXT}/api/safesite/user/updateUser`,
                  this.userInfo)
                .then((resp) => {
                  if (resp.data.success) {
                    layer.msg(resp.data.message);
                    $scope.closeThisDialog();
                    $state.go('login');
                  } else {
                    layer.alert(resp.data.message);
                  }
                });
            }
          };

          // 初始化页面
          this.initPage = () => {
            // 获取登陆用户信息
            this.getUserInfo();
          }

          this.initPage();

        }
      });
    }

    // 二维码
    this.qrCode = () => {
      ngDialog.openConfirm({
        template: 'codeDialog',
        className: 'ngdialog-theme-default pa-confirm-theme codeDialog',
        controllerAs: 'vm',
        controller: function($scope) {
          'ngInject';

          // 下载用户手册
          this.getDocx = () => {
            return `${SERVER_IP}/uploadfile/平安工程APP用户手册.docx`;
          }

          // 获取二维码图片 平安/锡通
          this.getCodeImg = () => {
            let localHost = location.host;
            let qrContent = encodeURIComponent(`http://${localHost}/apk/app.apk`);
            let requestUrlStr =
            `${SERVER_CONTEXT}/api/qr?size=160&code=${qrContent}`;
            return requestUrlStr;
          }
        },
      })
    }

    // 退出
    this.logout = () => {
      authenticate.logout();
    }

    this.getMsgNum = () => {
      $http
        .post(`${SERVER_CONTEXT}/api/user/app/message/queryUnreadNum`, {
          isRead: 0
        })
        .success((data) => {
          this.msgCount = data;
        })
    }

    $rootScope.$on('read-msg', () => {
      if (this.msgCount) {
        this.msgCount--;
      }
    })

    // 用户登录成功再请求实时刷新
    // $interval(this.getMsgNum, 5000);
    this.getMsgNum();
    $interval(function(){
      if ($rootScope.isLogined) {
        _this.getMsgNum();
      }
    },30000);
  }
  return directive;
}

export default headerNavComponent;